<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="问卷标题" prop="title">
              <el-input v-model="queryParams.title" placeholder="请输入问卷标题" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:questionnaire:add']" type="primary" plain icon="Plus" @click="handleAdd"> 新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:questionnaire:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:questionnaire:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:questionnaire:export']" type="warning" plain icon="Download" @click="handleExport">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="questionnaireList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="true" label="主键id" align="center" prop="id" />
        <el-table-column label="问卷标题" align="center" prop="title" />
        <el-table-column label="问卷封面" align="center" prop="photoUrl" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.photoUrl" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['system:questionnaire:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="题目配置" placement="top">
              <el-button v-hasPermi="['system:questionnaire:topic']" link type="primary" icon="Refresh" @click="topicEdit(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['system:questionnaire:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>

    <!-- 添加或修改问卷对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="questionnaireFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="问卷标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入问卷标题" />
        </el-form-item>
        <el-form ref="questionnaireFormRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="问卷封面" prop="photo">
            <image-upload v-model="form.photo" limit="1" />
          </el-form-item>
        </el-form>
        <el-form-item label="答题结果" prop="results">
          <div v-for="(result, index) in form.resultsJson" :key="index" class="flex items-center mb-2">
            <el-input v-model="result.title" placeholder="标题" style="width: 100px" />
            <el-input v-model="result.score" placeholder="分数" style="width: 100px" />
            <el-input v-model="result.hint" placeholder="提示文本" style="width: 100px" />
            <el-button v-if="index === 0" type="text" @click="addResult">+</el-button>
            <el-button v-if="index !== 0" type="text" @click="removeResult(index)">-</el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改问卷对话框 -->

    <el-dialog v-model="topDialog.visible" :title="topDialog.title" width="800px" append-to-body>
      <el-form ref="questionnaireFormRef" :model="form" label-width="80px">
        <div>
          <div v-for="(question, qIndex) in form.topicJson" :key="qIndex">
            <el-form-item :label="'题目' + (qIndex + 1) + ':'" prop="title" class="flex-item">
              <div class="flex-container">
                <el-input v-model="question.title" placeholder="请输入题目标题" class="input-with-button" />
                <el-button type="text" class="inline-button" @click="removeQuestion(qIndex)">删除题目</el-button>
              </div>
            </el-form-item>
            <ul>
              <li v-for="(option, oIndex) in question.topic" :key="oIndex" class="option-container">
                <el-form-item label="答案:" prop="title" class="form-item" style="width: 45.5%">
                  <el-input v-model="option.title" placeholder="请输入答案" />
                </el-form-item>
                <el-form-item label="分数:" prop="score" class="form-item">
                  <el-input v-model="option.score" placeholder="请输入分数" />
                </el-form-item>
                <el-button v-if="oIndex === 0" type="text" class="inline-button" @click="addOption(qIndex)">+ </el-button>
                <el-button v-if="oIndex !== 0" type="text" class="inline-button" @click="removeOption(qIndex, oIndex)"> - </el-button>
              </li>
            </ul>
          </div>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="addQuestion">新增题目</el-button>
          <el-button @click="topCancel">取 消</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Questionnaire" lang="ts">
import { ref, reactive, toRefs, onMounted } from 'vue';
import { ElForm, ElFormItem, ElInput, ElButton, ElDialog, ElCard, ElTable, ElTableColumn, ElRow, ElCol, ElTooltip, ElMessage } from 'element-plus';
import { listQuestionnaire, getQuestionnaire, delQuestionnaire, addQuestionnaire, updateQuestionnaire } from '@/api/system/questionnaire';
import { QuestionnaireVO, QuestionnaireQuery, QuestionnaireForm } from '@/api/system/questionnaire/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const questionnaireList = ref<QuestionnaireVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElForm>();
const questionnaireFormRef = ref<ElForm>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const topDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: QuestionnaireForm = {
  id: undefined,
  title: undefined,
  resultsJson: [{} as Result],
  results: '',
  topicJson: [] as ToPicResult[],
  topic: ''
};

const data = reactive<PageData<QuestionnaireForm, QuestionnaireQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键id不能为空', trigger: 'blur' }],
    title: [{ required: true, message: '问卷标题不能为空', trigger: 'blur' }],
    resultsJson: [{ required: true, message: '答题结果不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

interface Result {
  title: string;
  score: string;
  hint: string;
}

interface ToPicResult {
  title: string;
  topic: Array<{
    title: string;
    score: number;
  }>;
}

const addResult = () => {
  form.value.resultsJson.push({ title: '', score: '', hint: '' });
};

const removeResult = (index: number) => {
  form.value.resultsJson.splice(index, 1);
};

const getList = async () => {
  loading.value = true;
  const res = await listQuestionnaire(queryParams.value);
  questionnaireList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

const cancel = () => {
  reset();
  dialog.visible = false;
};

const topCancel = () => {
  reset();
  topDialog.visible = false;
};

const reset = () => {
  form.value = { ...initFormData };
  questionnaireFormRef.value?.resetFields();
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleSelectionChange = (selection: QuestionnaireVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加问卷';
};

const handleUpdate = async (row?: QuestionnaireVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getQuestionnaire(_id);
  form.value.resultsJson = JSON.parse(res.data.results);
  form.value.topicJson = JSON.parse(res.data.topic);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改问卷';
};

const topicEdit = async (row?: QuestionnaireVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getQuestionnaire(_id);
  form.value.resultsJson = JSON.parse(res.data.results);
  form.value.topicJson = JSON.parse(res.data.topic);
  form.value = { ...initFormData, ...form.value };
  Object.assign(form.value, res.data);
  console.log(toRaw(form.value.topicJson));
  topDialog.visible = true;
  topDialog.title = '编辑题目';
};

const submitForm = () => {
  questionnaireFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      // 将 results 转换为 JSON 字符串
      // resultsJson 不为空数组的时候复制
      form.value.results = JSON.stringify(form.value.resultsJson);
      form.value.topic = JSON.stringify(form.value.topicJson);
      if (form.value.id) {
        await updateQuestionnaire(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addQuestionnaire(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      topDialog.visible = false;
      await getList();
    }
  });
};

const handleDelete = async (row?: QuestionnaireVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除问卷编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delQuestionnaire(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

const handleExport = () => {
  proxy?.download(
    'system/questionnaire/export',
    {
      ...queryParams.value
    },
    `questionnaire_${new Date().getTime()}.xlsx`
  );
};

const addQuestion = () => {
  form.value.topicJson.push({
    title: '',
    topic: [{ title: '', score: 1, off: false }]
  });
};

const addOption = (qIndex: number, oIndex: number) => {
  form.value.topicJson[qIndex].topic.push({
    title: '',
    score: form.value.topicJson[qIndex].topic.length + 1,
    off: false
  });
};

const removeOption = (qIndex: number, oIndex: number) => {
  form.value.topicJson[qIndex].topic.splice(oIndex, 1);
};

const removeQuestion = (qIndex: number) => {
  form.value.topicJson.splice(qIndex, 1);
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.flex {
  display: flex;
  align-items: center;
}

.mb-2 {
  margin-bottom: 10px;
}

.option-container {
  display: flex;
}

.form-item {
  margin: 0 10px; /* 在表单项之间添加一些间距 */
}

.input-with-button {
  flex: 1;
  margin-right: 10px; /*在输入框和按钮之间添加一些间距 */
}

.inline-button {
  margin-left: 10px; /* 在按钮之间添加一些间距 */
}

.flex-container {
  display: flex;
  align-items: center;
  width: 100%;
}
</style>
